﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vds2465Telegrams;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_56_IdentificationNumber
	{
		#region constants

		private const int NrOfHeaderBytes = 2;

		#endregion constants

		#region internal methods

		internal static byte[] GenerateBytes(UserData userData)
		{
			byte[] userDataBytes = null;

			if (userData is UserData_56_IdentificationNumber)
			{
				UserData_56_IdentificationNumber userData56 = userData as UserData_56_IdentificationNumber;
				byte[] idNumberBytes = GenParse_Helper.GenerateNumberBytes(userData56.IdentificationNumber);

				byte nrOfBytes = (byte)(NrOfHeaderBytes + idNumberBytes.Length);

				userDataBytes = new byte[nrOfBytes];
				userDataBytes[0] = (byte)(nrOfBytes - GenParse_UserData.HeaderLength);	// user data length
				userDataBytes[1] = UserData.UserData56IdentificationNumber;
				for (int index = 0; index < idNumberBytes.Length; index++)
				{
					userDataBytes[2 + index] = idNumberBytes[index];
				}
			}
			else
			{
				// TODO handle error
			}

			return userDataBytes;
		}

		internal static bool ParseBytes(byte[] userDataBytes, out UserData userData56, out int consumedBytes)
		{
			userData56 = null;
			consumedBytes = 0;

			if (userDataBytes.Length >= NrOfHeaderBytes)
			{
				byte setLength = userDataBytes[0];
				if (userDataBytes.Length >= setLength + 2)
				{
					if (userDataBytes[0] > 0)
					{
						// first byte                
						if (userDataBytes[1] == UserData.UserData56IdentificationNumber)
						{
							int nrOfIdNumberBytes = userDataBytes[0];
							byte[] idNumberBytes = new byte[nrOfIdNumberBytes];
							for (int index=0; index < nrOfIdNumberBytes; index++)
							{
								idNumberBytes[index] = userDataBytes[2 + index];
							}
							string idNumberString = GenParse_Helper.ParseNumberBytes(idNumberBytes);

							userData56 = new UserData_56_IdentificationNumber(idNumberString);
							consumedBytes = NrOfHeaderBytes + nrOfIdNumberBytes;
							return true;
						}

						// wrong value for the data type
						return false;

					}

					// TODO handle error (wrong value in first byte the length)
					return false;
				}

				// TODO handle error: not enough bytes as specified by the SL value
				return false;
			}

			// TODO handle error (not enough bytes)
			return false;
		}

		#endregion internal methods
	}
}
